/**
 * 初始化简历整体数据
 */
define(function(){
    var ec=require('echarts');
    require('echarts/chart/line');
    require('echarts/chart/bar');
    require('echarts/chart/pie');
    
    var ecConfig = require('echarts/config');
    var zrUtil = require('zrender/tool/util');
    var zrnumber = require('echarts/util/number');

    var myChart_pie = ec.init(document.getElementById('income1_pie'));
    var myChart_line = ec.init(document.getElementById('income1_line'));

//饼图的数据模版
    var option_pie_one= {
        title : {
            text: '',
            x:'center',
            y:'380'
        },
        tooltip : {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
            x : 'left',
            data:[]
        },
        calculable : true,
          toolbox: {
                show : true,
                orient:'vertical',
                y:'bottom',
                feature : {
                    mark : {show: false},
                    dataView : {show: true, readOnly: false},
                    magicType : {
                        show: true, 
                        type: ['pie', 'funnel'],
                        option: {
                            funnel: {
                                x: '25%',
                                width: '50%',
                                funnelAlign: 'left',
                                max: 1548
                            }
                        }
                    },
                    restore : {show: true},
                    saveAsImage : {show: true}
                }
            },
        series : [
            {
                name:'',
                type:'pie',
                radius : '45%',
                center: ['50%', 200],
                data:[]
            }
        ]
    };

//带timeline的饼图模版   
    var option_pie = {
        timeline : {
            type:"number",
            height:40,
            symbolSize:3,
                x:"1%",
                x2:"1%",
                width:"80%",
                label:{
                        interval: 'auto',
                        formatter:function(param){
                            return param;
                        }
                },
                data : ['']
        },  
        options:[]
    };
      
//堆积图   
    var option_line = {
                tooltip : {
                    trigger: 'axis'
                },
                legend: {
                    data:[]
                },
                toolbox: {
                    show : true,
                    orient:'vertical',
                    y:'bottom',
                    feature : {
                        mark : {show: false},
                        dataZoom : {show: false},
                        magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                        restore : {show: true},
                        saveAsImage : {show: true}
                    }
                },
                grid: {
                    x: 60,
                    x2:40
                },                    
                calculable : true,
                xAxis: [{
                    type: "category",
                    boundaryGap: true,
                    data : [],
                    axisLabel:{formatter:function(value){
                        return value;
                    }}
                }],
                yAxis : [
                    {
                        type : 'value'
                    }
                ],
                series : [
                    {
                        name: '',
                        type: 'bar',
                        smooth: true,
                        symbol:'none',
                        data: []
                    },
                    {
                        name: '',
                        type: 'bar',
                        smooth: true,
                        symbol:'none',
                        data: []
                    }
                ]
            };
         
    function showPie(){
        
        var city = $('#income1_city').val();
        
        myChart_pie.showLoading({
            text: '正在努力的读取数据中...'
        });
        $.ajax({
            url: '/dashboard/resume/ajax/incomePie',
            type: 'POST',
            async: true,
            data:{"city":city,"type":1},
            dataType: 'json',
            success: function(data, textStatus) {

                    //设置饼图
                    setPie(data);
                    myChart_pie.hideLoading();
                    
                    //设置堆积图                   
                    show_line(2);     
                    
             },
             timeout: 5000,
             error: function() {
                 myChart_pie.hideLoading();
             }
          });
}

//设置饼图数据
    function setPie(data){
        option_pie.options=[];
        //饼图时间轴
        option_pie.timeline.data=data.timeline;
        option_pie.timeline.currentIndex=data.timeline.length-1;   
        
        //饼图数据
        $.each(data.options,function(index,value){
            var option= zrUtil.clone(option_pie_one);
          
            option.series[0].name=data.timeline[index];
            option.series[0].data = value;
            
            option.legend.data = data.cate;   
                 
            option_pie.options.push(option);
         });
        
         myChart_pie.setOption(option_pie,true);

    }

    var legendData=['总收入','现金收入'];

    /**
    * 根据指标显示日数据
    * @param eventType= 2:第一次加载, 1:切换日，周，月刷新 , 0: 添加对比后又重新选择指标
    */
    function show_line(eventType){
        var dateGrp = $('#income1_option').attr('dateGrp'); //日月周的选项
        var city = $('#income1_city').val();
        var index1 = $('#income1_userType').val();      
        var index2 = $('#income1_index').val();
        
        myChart_line.showLoading({ text: '正在努力的读取数据中...' });
        $.ajax({
            url:'/dashboard/resume/ajax/incomeLine',
            type: 'post',
            async: true,
            data:{"dateGroup":dateGrp,"type":1,"city":city, "index1":index1,"index2":index2},
            dataType: 'json',
            success: function(data, textStatus) {
                //X轴时间
                option_line.xAxis[0].data = data.time;
                option_line.legend.data = legendData;

                 option_line.series[0].name = legendData[0];
                 option_line.series[1].name = legendData[1];  

                 option_line.series[0].data=data.line1Data;
                 option_line.series[1].data=data.line2Data;
                

                option_line.tooltip.formatter=tooltipFunc;
                    
                //区域缩放
                var datezoom_local={
                    stat_date:{start:(1-7/data.time.length)*100,end:100},
                    week_begin:{start:(1-7/data.time.length)*100,end:100},
                    month_num:{start:0,end:100}
                };
                //少于31个点，全显
                if(data.time.length<7){
                    datezoom_local={
                        stat_date:{start:0,end:100},
                        week_begin:{start:0,end:100},
                        month_num:{start:0,end:100}
                    };
                }
             
                if(eventType == 1 || eventType == 2){
                    if('stat_date'==dateGrp || 'week_begin'==dateGrp){      
                        option_line.xAxis[0].axisLabel.formatter=function(value){ return value; } ;
                    }else if('month_num'==dateGrp){
                        option_line.xAxis[0].axisLabel.formatter=function(value){ return value.substr(0,4)+"年"+value.substr(4,2)+"月"; } ;
                    }
                       
                    if(eventType == 1 && myChart_line.component.dataZoom){
                        option_line.dataZoom=datezoom_local[dateGrp];
                        myChart_line.component.dataZoom.absoluteZoom(datezoom_local[dateGrp]);
                        option_line.dataZoom.show=true;
                    }else if(eventType == 2){
                        option_line.dataZoom=datezoom_local[dateGrp];
                        option_line.dataZoom.show=!$('#time_checkbox_income1').is(":checked");
                    }
                    
                    myChart_line.setOption(option_line,true);                     
                }else if(eventType == 0){
                    myChart_line.component.dataZoom=compDataZoom_old;
                    myChart_line.setOption(option_line,true);
                    if($('#time_input_income1').val()){
                        EC.addCompare($('#time_input_income1').val());
                    }
                }  
                
                myChart_line.hideLoading();

            },
            error : function() {
                myChart_line.hideLoading();
            }
        });
    }
        
  //提示框
    function  tooltipFunc(params, ticket, callback){
        var dateVal = formatShowDate(params[0].name);
        var curOption = option_line;
        var index_current=getIndexByName(curOption.xAxis[0].data,params[0].name);

        var result='<table class="table-center">';
        result+='<tr><td>'+dateVal+'</td><td>';
        var isStatDay = isDay(); 
        if(isStatDay)
            result += getWeekDay(dateVal);
        result += '</td>';
        if(isStatDay)
            result +="<td>日环比</td><td>周同比</td>";
        else if(isWeek())
            result += "<td>周环比</td>";
         else if(isMonth())
            result += "<td>月环比</td><td>月同比</td>";
        result += '</tr>';


        $(params).each(function(index,para){
            result+='<tr><td>'+para.seriesName+'</td><td>'+zrnumber.addCommas(para.data)+'</td>';
            var seriesIndex = para.seriesIndex;
            var day_td="<td>--</td>";
            //日周月 环比(前一日周月)
            if(index_current-1>=0){
                var data_yesday = null;
                data_yesday= curOption.series[seriesIndex].data[index_current-1];                
                if(data_yesday != null){
                    var s=(((para.data/data_yesday)-1)*100).toFixed(2);
                    if(s>0){
                        day_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                    }else{
                        day_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                    }
                }
            }
            result += day_td;
            //周同比(日)
             if(isStatDay){
                 var week_td='<td>--</td>';
                 if(index_current-7>=0){
                     data_week= curOption.series[seriesIndex].data[index_current-7];
                     var s=(((para.data/data_week)-1)*100).toFixed(2);
                     if(s>0){
                         week_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                     }else{
                         week_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                     }
                 }
                 result += week_td;
             }                
            result += '</tr>';
        });
        result+='</table>';
        return result;
    }        
        
    function formatShowDate(yyyymmdd){
         var dateGrp = $('#income1_option').attr('dateGrp');
                
        if('stat_date'==dateGrp){
            return yyyymmdd;
        }else if('week_begin'==dateGrp){
            return yyyymmdd;
        }else if('month_num'==dateGrp){
            return yyyymmdd.substr(0,4)+"年"+yyyymmdd.substr(4,2)+"月";
        }
    }

    function isDay(){
        var dateGrp = $('#income1_option').attr('dateGrp');
        if('stat_date'==dateGrp){
            return true;
        }
        return false;
    }

    function isWeek(){
        var dateGrp = $('#income1_option').attr('dateGrp');
        if('week_begin'==dateGrp){
            return true;
        }
        return false;
    }

    function isMonth(){
        var dateGrp = $('#income1_option').attr('dateGrp');
        if('month_num'==dateGrp){
            return true;
        }
        return false;
    }

    var zrUtil = require('zrender/tool/util');
        // console.log(zrUtil);

    function getShowDays(){
        return compDataZoom_old.option.xAxis[0].data;
    }
        
    function addCompare(time){
        time=formatTime(time);
        var copy=zrUtil.clone(option_line);
        copy.toolbox.feature.magicType.show=false;
        copy.toolbox.feature.dataZoom.show=false;
        var index_time=getIndexByName(option_line.xAxis[0].data,time);
        var index_show=getIndexByName(option_line.xAxis[0].data,getShowDays()[0]);
        var length=getShowDays().length;
        setCompareXaxis(copy,index_time,index_show,length);
        var index=0;
        //选中对比时，再次选择指标，需要记忆图例的选择状态
        $.each(legend_SelectedMap,function(key,value){
            //判断是否在当前图例值中，应为echarts会把"对比时间段"也放入SelectedMap
            if($.inArray(key,option_line.legend.data) != -1){
                if(value){
                    return false;
                }
                index++;
            }     
        });
        
        if(index<option_line.legend.data.length){
            setCompareSeries(copy,index,index_time,index_show,length);
            setCompareLegend(copy);
            setCompareTooltip(copy);
            delete copy.dataZoom;
            myChart_line.restore();
            myChart_line.setOption(copy,true);
        }

    }

    function setCompareLegend(copy){
        copy.legend= {
            data:[copy.series[0].name, copy.series[1].name],
            selectedMode:false
        }
    }

    var compDataZoom_old;
    var legend_SelectedMap={};  //需要记忆图例的选择状态
    function hideDataZoom(){
        legend_SelectedMap=myChart_line.component.legend.getSelectedMap();
        compDataZoom_old=myChart_line.component.dataZoom;    //记忆缩放
        option_line.dataZoom.show=false;
        myChart_line.setOption(option_line,false);
    }

    function removeCompare(){
        //恢复缩放
        myChart_line.component.dataZoom=compDataZoom_old;
        option_line.dataZoom.show=true;
        //去掉对比时恢复图例的选择状态
        $.each(legend_SelectedMap,function(key,value){
            if($.inArray(key,option_line.legend.data) != -1){
                myChart_line.component.legend.setSelected(key,value);
            }else{
                myChart_line.component.legend.setSelected(key,false);
            }
        });
        myChart_line.setOption(option_line,true);
    }


    function setCompareTooltip(copy){
        copy.series[1]&&copy.series[1].tooltip&&(copy.series[1].tooltip={show:false});
        copy.series[2]&&copy.series[2].tooltip&&(copy.series[2].tooltip={show:false});
        copy.series[3]&&copy.series[3].tooltip&&(copy.series[3].tooltip={show:false});

        copy.tooltip.formatter=function(params, ticket, callback){
            var date_current=params[0][1];
            var data_current=params[0][2];
            var index_current=getIndexByName(copy.xAxis[0].data,date_current);
            
            var dateVal = formatShowDate(date_current);
            var result='<table class="table-center">' +
                '<tr><td>'+dateVal;
            //是日要显示周几
            if(isDay())
                 result += ' ('+getWeekDay(dateVal)+')';
            result += '</td><td>'+zrnumber.addCommas(data_current)+'</td></tr>';
            if(copy.series[1]){
                var data_compare=copy.series[1].data[index_current];
                var s=(((data_current-data_compare)/data_compare)*100).toFixed(2);
                dateVal = formatShowDate(copy.xAxis[1].data[index_current]);
                result+='<tr><td>'+dateVal;
                if(isDay())
                    result += ' ('+getWeekDay(dateVal)+')';
                result += '</td><td>'+zrnumber.addCommas(data_compare)+'</td></tr>';
                if(s>0){
                    result+='<tr><td>变化</td><td style="color: orangered">'+s+'%&#8593</td></tr>';
                }else{
                    result+='<tr><td>变化</td><td style="color: greenyellow">'+s+'%&#8595</td></tr>';
                }
            }
            result+='</table>';
            return   result;
        }
    }

    function  setCompareSeries(copy,index,index_time,index_show,length){
        copy.series=[];
        //原来数据
        copy.series.push(zrUtil.clone(option_line.series[index]));
        copy.series[0].type='line';
        copy.series[0].data=option_line.series[index].data.slice(index_show,index_show+length);
        delete  copy.series[0].stack;
        delete  copy.series[0].itemStyle;
        //对比数据
        copy.series.push(zrUtil.clone(option_line.series[index]));
        copy.series[1].type='line';
        copy.series[1].name="对比时间段";
        copy.series[1].xAxisIndex=1;
        delete  copy.series[1].stack;
        delete  copy.series[1].itemStyle;

        copy.series[1].data=option_line.series[index].data.slice(index_time,index_time+length);
        if(length>31){return}
        //对比柱
        copy.series.push({
            tooltip:{show:false},
            show:false,
            name: '对比时间段1',
            type: 'bar',
            stack: '1',
            barWidth:3,
            xAxisIndex:1,
            itemStyle:{
                normal:{
                    color:'rgba(0,0,0,0)'
                },
                emphasis:{
                    color:'rgba(0,0,0,0)'
                }
            },
            data: function(){
                var i=0;
                return $.map(copy.series[1].data,function(val){
                    var tt=copy.series[0].data[i++];
                    if(val<tt){
                        return val;
                    }else{
                        return tt;
                    }
                })
            }()
        });
        copy.series.push({
            tooltip:{show:false},
            name: '变化',
            type: 'bar',
            stack: '1',
            xAxisIndex:1,
            data: function(){
                var i=0;
                return $.map(copy.series[1].data,function(val){
                    var tt=copy.series[0].data[i++];
                    if(val<tt){
                        return tt-val;
                    }else{
                        return {value : val-tt, itemStyle:{ normal:{color:'red'}}};
                        //return val-tt;
                    }
                })
            }()
        });
    }

    function setCompareXaxis(copy,index_time,index_show,length){
        copy.xAxis=[];
        copy.xAxis.push(zrUtil.clone(option_line.xAxis[0]));
        copy.xAxis.push(zrUtil.clone(option_line.xAxis[0]));
        copy.xAxis[0].data=option_line.xAxis[0].data.slice(index_show,index_show+length);
        copy.xAxis[1].data=option_line.xAxis[0].data.slice(index_time,index_time+length);
    }      
        
    //双Y轴时要重新设置Y轴名称
    function setCompareYaxis(copy,index){
        var yAxisName = copy.yAxis[index].name;
        copy.yAxis.forEach(function(value){
            value.name=yAxisName;
        }); 
    }
    
    function getIndexByName(data,name) {
        var dataLength = data.length;
        for (var i = 0; i < dataLength; i++) {
            if (data[i] == name || typeof data[i].value != 'undefined' && data[i].value == name) {
                return i;
            }
        }
        return -1;
    }
        
        
    function formatTime(time){
        return time;
    }

    function getAllDays(){
        return option_line.xAxis.data||option_line.xAxis[0].data;
    }

    // 时间勾选框事件
    $('#time_checkbox_income1').change(function(e){
        var input=$('#time_input_income1');
        if(!input)return;
        if($(this).is(":checked")){
            input.removeAttr('disabled');
            input.attr('placeholder','选择时间起点');               
            EC.hideDataZoom();
            setDatePicker(EC, $('#income1_option').attr('dateGrp'),input);
        }else{
            input.val('');
            input.attr('disabled','');
            input.attr('placeholder','添加对比');               
            EC.removeCompare();
        }
    });
     
    $(":button.btn_income1[dateGrp]").click(function(){
        changeDateGrp(this);
        $('#time_checkbox_income1').attr('checked',false);
        $('#time_input_income1').val('');
        $('#time_input_income1').attr('disabled','');
        if($(this).attr('dateGrp')=='week_begin'){
            $('#time_input_income1').parent().css('visibility',"hidden");
        }else{
            $('#time_input_income1').parent().css('visibility',"visible");
        }
        show_line(1);
    });

    //对比时间选择事件
    $('#time_input_income1').datepicker().on('changeDate',function(e){
        EC.addCompare(e.format());
    });
    
    //刷新
   $("#refresh_income1_btn").click(function(){
        var type = 2;
        if($('#time_checkbox_income1').is(":checked"))
            type=0;        
        show_line(type);
    });
    
     var EC={
        show:showPie,
        resize:function(){myChart_pie.resize();myChart_line.resize();},
        hideDataZoom:hideDataZoom,
        removeCompare:removeCompare,
        getShowDays:getShowDays,
        getAllDays:getAllDays,
        addCompare:addCompare
    };
    
    return EC;
});